package controller;

import business.ebi.UserEBI;
import business.factory.BusinessFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;

@WebServlet(name = "RegisterController",urlPatterns = "/registerController")
public class RegisterController extends HttpServlet {
    private final UserEBI ebi = BusinessFactory.getUserEBI();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("method");
        if (action!=null) {
            try {
                Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
                method.invoke(this, req, resp);
            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        resp.setContentType("text/html;charset=utf8");
        String username = req.getParameter("username");
        if (!ebi.check(username)){
            String password = req.getParameter("password");
            ebi.insert(username,password);
            resp.sendRedirect("/login.html");
        }else {
            resp.getWriter().write("<script language=javascript>alert('" +"用户名已存在!点击确定前往登录页面"+ "');window.location='login.html'</script>");
        }
    }

    protected void forget(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException {
        resp.setContentType("text/html;charset=utf8");
        resp.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        if (ebi.check(username)){
            String password = req.getParameter("password");
            ebi.update(username,password);
            resp.sendRedirect("/login.html");
        }else {
            resp.getWriter().write("<script language=javascript>alert('" +"用户名不存在!点击确定前往注册页面"+ "');window.location='Register.jsp'</script>");
        }
    }
}
